var express = require('express');
var router = express.Router();
var db = require('../db.js');

/* GET users listing. */
// add
router.all('/add',function(req,res){
  if(req.method=="POST"){
    var reqData=req.body;
  }else{
    var reqData=req.query||req.params
  }
  console.log(reqData)
  db.BAdmin.find({
    user_id:reqData.query.user_id,
    topic_id:reqData.query.topic_id,
  }).sort({_id:-1}).then(function(adminData){
    var can=true;    
    if(adminData.length>0){
      var perDate=Date.parse(adminData[0].date)
      if(Date.now()-perDate<24*3*60*60*1000){
        can=false;
      }    
    }
    if(!can){
      res.json({
        code:1005,
        msg:'你已经申请过该话题的版主，3天内请勿再次申请'
      })
    }else{
      var newBAdmin=new db.BAdmin(reqData.query);
      newBAdmin.save().then(function(){
        res.json({
          code:200,
          msg:'申请成功，请耐心等待审批'
        })
      })
    }
    
  })
})
router.all('/updata',function(req,res){
  if(req.method=="POST"){
    var reqData=req.body;
  }else{
    var reqData=req.query||req.params
  }
  console.log('notejs 92',reqData)
  db.BAdmin.findOneAndUpdate(reqData.query,reqData.data).then(function(data){
    res.json({
      code:200,
      msg:'提交成功',
      data
    })
  })
})
router.all('/query', function (req, res) {
  if (req.method == "POST") {
    var reqData = req.body;
  } else {
    var reqData = req.query || req.params;
  }
  var pageNum=reqData.pageNum*1||1;
  var pageSize=reqData.pageSize*1||20;
  if(!!reqData.query&&!!reqData.query.$reg){
    for (const key in reqData.query.$reg) {
      if (reqData.query.hasOwnProperty(key)) {
        reqData.query[key]=new RegExp(reqData.query[key],'i')    
      }
    }
    delete reqData.query.$reg;
  }
  db.BAdmin.find(reqData.query||{}).then(function(data){
    var pageCount=Math.ceil(data.length/pageSize);
    pageNum=pageNum>pageCount?pageCount:pageNum;
    db.BAdmin.find(reqData.query||{}).sort({'_id':-1}).skip((pageNum==0?0:pageNum-1)*pageSize).limit(pageSize).then(function(data){
      res.json({
        code:200,
        pageNum:pageNum,
        pageSize,
        pageCount,
        data
      })
    })
  })
})
router.all('/fuzzy', function (req, res) {
  if (req.method == "POST") {
    var reqData = req.body;
  } else {
    var reqData = req.query || req.params;
  }
  db.BAdmin.find({ name: { $regex: reqData.query.name }, statu:{"$ne":"baned"}}).then(function(data){
    res.json({ 
      code:200,
      data: data 
    })
  })
})


module.exports = router;